package nccloud.mob.riart.message.actions;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import itf.approvecenter.util.DataExchangeBean;
import nc.bs.logging.Log;
import nc.bs.pf.pub.PfDataCache;
import nc.itf.uap.IUAPQueryBS;
import nc.itf.uap.pf.IWorkflowAdmin;
import nc.itf.uap.pf.IWorkflowDefine;
import nc.vo.jcom.lang.StringUtil;
import nc.vo.ml.NCLangRes4VoTransl;
import nc.vo.pub.AggregatedValueObject;
import nc.vo.pub.BusinessException;
import nc.vo.pub.workflownote.WorkflownoteVO;
import nc.vo.wfengine.core.activity.Activity;
import nc.vo.wfengine.core.parser.UfXPDLParser;
import nc.vo.wfengine.core.serializer.UfXPDLSerializer;
import nc.vo.wfengine.core.workflow.BasicWorkflowProcess;
import nc.vo.wfengine.core.workflow.WorkflowProcess;
import nc.vo.wfengine.ext.ApproveFlowAdjustVO;
import nccloud.commons.lang.StringUtils;
import nccloud.framework.core.exception.ExceptionUtils;
import nccloud.framework.mob.action.itf.IMobileAction;
import nccloud.framework.mob.container.IMobRequest;
import nccloud.framework.mob.container.MobClientInfo;
import nccloud.framework.service.ServiceLocator;
import nccloud.framework.web.action.itf.ICommonAction;
import nccloud.framework.web.container.IRequest;
import nccloud.framework.web.container.SessionContext;
import nccloud.itf.uap.pf.NCCWorkFlowService;
import nccloud.web.workflow.approvalcenter.action.ApplicationRuntimeAdjustContext;
import nccloud.web.workflow.approvalcenter.action.PfChecknoteEnum;
import nccloud.web.workflow.approve.util.NCCFlowUtils;
import nccloud.web.workflow.approve.util.NCCMsgContext;

public class ApproveAddApproverAction
implements ICommonAction, IMobileAction
{
	private Log msginstance = Log.getInstance("msglog");
	WorkflownoteVO m_workflow = null;


	@Override
	public Object doAction(IRequest request) {
		String jsonStr = request.read();
		String cuserid = SessionContext.getInstance().getClientInfo().getUserid();

		return doAddApprover(jsonStr, cuserid, false);
	}






	@Override
	public Object doAction(IMobRequest req) {
		String jsonStr = req.read();
		String cuserid = (new MobClientInfo()).getUserid();


		return doAddApprover(jsonStr, cuserid, true);
	}




	private WorkflownoteVO adjust(ApplicationRuntimeAdjustContext context) throws BusinessException {
		ApproveFlowAdjustVO vo;
		this.m_workflow = context.getWorkFlow();
		String processDefPK = this.m_workflow.getTaskInfo().getTask().getWfProcessDefPK();
		String processInstPK = this.m_workflow.getTaskInfo().getTask().getWfProcessInstancePK();
		String activityDefPK = this.m_workflow.getTaskInfo().getTask().getActivityID();

		IUAPQueryBS dao = ServiceLocator.find(IUAPQueryBS.class);
		Collection<ApproveFlowAdjustVO> adjustVoCol = dao.retrieveByClause(ApproveFlowAdjustVO.class, "pk_wf_instance='" + processInstPK + "'");


		if (adjustVoCol == null || adjustVoCol.size() == 0) {
			vo = new ApproveFlowAdjustVO();
			vo.setPk_wf_instance(processInstPK);
		} else {
			vo = adjustVoCol.iterator().next();
		}

		try {
			BasicWorkflowProcess basicWorkflowProcess;
			if (StringUtil.isEmptyWithTrim(vo.getContent())) {
				basicWorkflowProcess = PfDataCache.getWorkflowProcess(processDefPK, processInstPK);
			} else {
				basicWorkflowProcess = UfXPDLParser.getInstance().parseProcess(vo.getContent());
			}

			Activity activity = basicWorkflowProcess.findActivityByID(activityDefPK);


			List<String> orgUnits = (List)context.getUserObject();

			addByCooperation(basicWorkflowProcess, activity, orgUnits);


			String content = UfXPDLSerializer.getInstance().serialize(basicWorkflowProcess);
			vo.setContent(content);


			ServiceLocator.find(IWorkflowDefine.class).saveProcessAfterAdjust(vo, basicWorkflowProcess);
			PfDataCache.synchronizeWorkflowProcess(processInstPK, basicWorkflowProcess);
			PfDataCache.synchronizeWorkflowProcess(processDefPK, null);
		} catch (Exception ex) {
			throw new BusinessException(ex);
		}
		return this.m_workflow;
	}









	private void addByCooperation(WorkflowProcess wp, Activity currentAct, List<String> userPKs) throws BusinessException {
		if (userPKs.size() == 0) {
			return;
		}
		ArrayList<String> approve_userIds = new ArrayList<String>();
		for (int i = 0; i < userPKs.size(); i++) {
			approve_userIds.add(userPKs.get(i));
		}
		this.m_workflow.getTaskInfo().getTask().setAddApprover(true);
		this.m_workflow.setExtApprovers(approve_userIds);

		ServiceLocator.find(IWorkflowAdmin.class).addApprover(this.m_workflow);
	}






	private Object doAddApprover(String jsonStr, String cuserid, boolean isMobile) {
		JSONObject json2 = JSON.parseObject(jsonStr);



		boolean isTrack = false;
		if (json2.get("isTrack") != null) {
			isTrack = json2.getBoolean("isTrack").booleanValue();
		}

		DataExchangeBean bean = new DataExchangeBean();
		bean.setCode("200");

		NCCMsgContext nccMsg = new NCCMsgContext(jsonStr);

		Map<String, Object> msgInfoMap = nccMsg.getMsgINfoContext();



		String[] flowParameterArray = { "billtype", "billid", "pk_checkflow" };


		if (NCCFlowUtils.isFlowParameterArrayNull(flowParameterArray, msgInfoMap)) {
			return NCCFlowUtils.exchangeDataMsg(bean, "500",
					NCLangRes4VoTransl.getNCLangRes().getStrByID("0020nccloud_0", "0ncc0020001-0428"));
		}

		String billType = msgInfoMap.get("billtype").toString();
		String billId = msgInfoMap.get("billid").toString();
		String pk_checkflow = msgInfoMap.get("pk_checkflow").toString();

		NCCFlowUtils.checkIsExistMessage(billType, billId, cuserid);


		List<String> add_approve_users = null;
		if (msgInfoMap.get("approve_users") != null) {
			add_approve_users = (List)msgInfoMap.get("approve_users");
		}


		if (add_approve_users == null || add_approve_users.size() == 0) {
			return NCCFlowUtils.exchangeDataMsg(bean, "500",
					NCLangRes4VoTransl.getNCLangRes().getStrByID("0020nccloud_0", "0ncc0020001-0429"));
		}







		NCCWorkFlowService nccWorkFlowService = ServiceLocator.find(NCCWorkFlowService.class);

		AggregatedValueObject billvo = null;


		try {
			if (!isMobile)
			{
				if (StringUtils.isNotBlank(pk_checkflow)) {
					String pk_group = nccWorkFlowService.getGroupByPKCheckFlow(pk_checkflow);
					if (StringUtils.isNotBlank(pk_group)) {
						SessionContext.getInstance().getClientInfo().setPk_group(pk_group);
					}
				}
			}

			this.m_workflow = nccWorkFlowService.checkWorkflowActions(billType, billId, pk_checkflow);
		}
		catch (BusinessException e) {
			msginstance.error("第三方调用移动端审批通过接口失败【nccloud.mob.riart.message.actions.ApproveAddApproverAction--doAddApprover】，失败原因【"+e.getMessage()+"】...........");
			return NCCFlowUtils.exchangeDataMsg(bean, "500", e.getMessage());
		}

		this.m_workflow.setTrack(isTrack);

		String checknote = "";
		if (msgInfoMap.get("checknote") == null ||
				StringUtil.isEmpty(String.valueOf(msgInfoMap.get("checknote")))) {
			checknote = NCCFlowUtils.getIndividualCheckNote(PfChecknoteEnum.ADDASSIGN, cuserid);
		} else {
			checknote = String.valueOf(msgInfoMap.get("checknote"));
		}

		this.m_workflow.setChecknote(checknote);
		ApplicationRuntimeAdjustContext context = new ApplicationRuntimeAdjustContext();
		this.m_workflow.setSenderman(cuserid);
		context.setStyle(3);
		context.setUserObject(add_approve_users);
		context.setWorkFlow(this.m_workflow);
		try {
			adjust(context);
		} catch (BusinessException e) {
			msginstance.error("第三方调用移动端审批通过接口失败【nccloud.mob.riart.message.actions.ApproveAddApproverAction---doAddApprover】，失败原因【"+e.getMessage()+"】...........");
			ExceptionUtils.wrapException(e);
		}



		return JSON.toJSON(bean);
	}
}